##=============================================================================
## Appendix Figure 27
##=============================================================================

##-----------------
# clear environment
rm(list=ls())
options(stringsAsFactors = FALSE, scipen = 999)
# source("R/functions.R")

seed <- sample.int(.Machine$integer.max, 1)
set.seed(seed)

ipak <- function(pkg){new.pkg <- pkg[!(pkg %in% installed.packages()[, "Package"])]
if(length(new.pkg)) install.packages(new.pkg, dependencies = TRUE)
sapply(pkg, require, character.only = TRUE)
}

packages <- c("tidyverse")

ipak(packages)

##---------
# Load data
#setwd("/Users/austinknuppe/Library/CloudStorage/Dropbox/Ukraine2022WartimeSurvey/Paper_peace/final_version_oct_2024/replication-scripts")
load("~/Desktop/clean_ukraine_data.RData")

plot <- dat %>% 
  filter(home_lang == 2 | home_lang == 3 | home_lang == 7) %>% 
  dplyr::select(id, wave, survival_mindset_z, save_lives_z) %>% 
  mutate(survival_binary = ifelse(survival_mindset_z > 0.71, 1, 0)) %>% 
  mutate(wave = factor(wave, labels = c("July 2022", "February 2023"))) %>%
  mutate(survival_binary = factor(survival_binary, labels = c("Low", "High"))) %>%
  drop_na(survival_binary) %>% 
  group_by(wave, survival_binary) %>% 
  summarise(mean = mean(save_lives_z, na.rm = TRUE), 
            sd = sd(save_lives_z, na.rm = TRUE), 
            n = sum(!is.na(save_lives_z))) %>% 
  mutate(se = sd / sqrt(n),
         lower = mean - qnorm(0.975) * se,
         upper  = mean + qnorm(0.975) * se) %>% 
  dplyr::select(wave, survival_binary, mean, lower, upper) 

ggplot(plot, aes(x = wave, y = mean, color = survival_binary,
                 group = survival_binary)) +
  geom_point(size = 5, position = position_jitterdodge(dodge.width = 0.1,
                                                       seed = 1234)) +
  geom_linerange(aes(x = factor(wave), ymin = lower, ymax = upper, 
                     color = factor(survival_binary)), lwd = 2,
                 position = position_jitterdodge(dodge.width = 0.1,
                                                 seed = 1234)) +
  labs(title = "Difference in Save Lives Between Waves Among Bilingual Respondents (Russian and Ukrainian)",
       y = "Save Lives (z-std)",
       x = "",
       color = "Survival Mindset") +
  hrbrthemes::theme_ipsum(axis_title_size = 18, base_size = 18, 
                          caption_size = 18, plot_title_size = 24) +
  geom_hline(yintercept = 0, colour = gray(1/2), size = 1, lty = 2) +
  scale_color_grey() +
  theme(legend.position = "bottom",
        legend.direction = "horizontal",
        panel.spacing = unit(0.1, "lines"),
        strip.text.x = element_text(size = 18)) +
  guides(color=guide_legend(override.aes=list(fill=NA)))

rm(list = ls())
##=============================================================================
## End of File
##=============================================================================